<template>
<ion-page :className="{ 'view-container': true, 'default-mode-view': true, 'demobportalview': true, 'crm-lead-mob-main-dashboard-view': true }">
    <ion-header>
        <ion-toolbar class="ionoc-view-header">
            <ion-buttons slot="start">
                <ion-button v-show="isShowBackButton" @click="closeView">
                    <ion-icon name="chevron-back"></ion-icon>
                    {{$t('app.button.back')}}
                </ion-button>
            </ion-buttons>
            <ion-title>{{$t(model.srfCaption)}}</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>
                <view_dashboard 
            :viewState="viewState"  
            :viewparams="viewparams" 
            :context="context" 
            name="dashboard"  
            ref='dashboard' 
            @load="dashboard_load($event)"  
            @closeview="closeView($event)">
        </view_dashboard>
    </ion-content>
</ion-page>
</template>

<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch } from 'vue-property-decorator';
import { Subject } from 'rxjs';
import GlobalUiService from '@/global-ui-service/global-ui-service';
import Crm_leadService from '@/app-core/service/crm-lead/crm-lead-service';

import MobPortalViewEngine from '@engine/view/mob-portal-view-engine';


@Component({
    components: {
    },
})
export default class Crm_leadMobMainDashboardViewBase extends Vue {

    /**
     * 全局 ui 服务
     *
     * @private
     * @type {GlobalUiService}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    private globaluiservice: GlobalUiService = new GlobalUiService();

    /**
     * 实体服务对象
     *
     * @type {Crm_leadService}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected appEntityService: Crm_leadService = new Crm_leadService();

    /**
     * 数据变化
     *
     * @param {*} val
     * @returns {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Emit() 
    protected viewDatasChange(val: any):any {
        return val;
    }

    /**
     * 视图上下文
     *
     * @private
     * @type {string}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Prop() private _context!: string;

    /**
     * 视图参数
     *
     * @private
     * @type {string}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Prop() private _viewparams!: string;

    /**
     * 视图默认使用
     *
     * @type {boolean}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Prop({ default: true }) protected viewDefaultUsage!: boolean;

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof Crm_leadMobMainDashboardViewBase
	 */
	protected viewtag: string = '6a3de46ef6f2a7beb2388d5efbd9d65b';

    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected context: any = {};

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected viewparams: any = {};

    /**
     * 是否显示部件视图头部，默认为false（显示）
     *
     * @type {boolean}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Prop({ default: false }) protected isShowViewHeader!: boolean;

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected model: any = {
        srfTitle: '线索/商机移动端数据看板视图',
        srfCaption: 'crm_lead.views.mobmaindashboardview.caption',
        srfSubCaption: '',
        dataInfo: ''
    }

    /**
     * 视图上下文变化
     *
     * @param {string} newVal
     * @param {string} oldVal
     * @memberof  Crm_leadMobMainDashboardViewBase
     */
    @Watch('_context')
    on_context(newVal: string, oldVal: string) {
        const _this: any = this;
        if (!Object.is(newVal, oldVal) && _this.engine) {
            _this.parseViewParam();
            _this.engine.load();
        }
        
    }

    /**
     * 视图参数变化
     *
     * @param {string} newVal
     * @param {string} oldVal
     * @returns
     * @memberof IBizChart
     */
    @Watch('_viewparams')
    on_viewparams(newVal: string, oldVal: string) {
        if (!Object.is(newVal, oldVal)) {
            if (!this.viewDefaultUsage && this._viewparams && !Object.is(this._viewparams, '')) {
                Object.assign(this.viewparams, JSON.parse(this._viewparams));
                return;
            }
        }
    }

    /**
     * 容器模型
     *
     * @type {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected containerModel: any = {
        view_dashboard: { name: 'dashboard', type: 'DASHBOARD' },
    };

    /**
     * 视图状态订阅对象
     *
     * @private
     * @type {Subject<{action: string, data: any}>}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected viewState: Subject<ViewState> = new Subject();




    /**
     * 解析视图参数
     *
     * @private
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    private parseViewParam(): void {
        if (!this.viewDefaultUsage && this._context && !Object.is(this._context, '')) {
            Object.assign(this.context, JSON.parse(this._context));
            return;
        }
        // 参数异常
        if (!this.viewDefaultUsage) {
            return;
        }

        const path = (this.$route.matched[this.$route.matched.length - 1]).path;
        const keys: Array<any> = [];
        const curReg = this.$pathToRegExp.pathToRegexp(path, keys);
        const matchArray = curReg.exec(this.$route.path);
        let tempValue: Object = {};
        keys.forEach((item: any, index: number) => {
            Object.defineProperty(tempValue, item.name, {
                enumerable: true,
                value: matchArray[index + 1]
            });
        });
        this.$viewTool.formatRouteParams(tempValue, this.$route, this.context, this.viewparams);
        //初始化视图唯一标识
        Object.assign(this.context, { srfsessionid: this.$util.createUUID() });
    }

    /**
     * 是否显示返回按钮
     *
     * @readonly
     * @type {boolean}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    get isShowBackButton(): boolean {
        // 存在路由，非路由使用，嵌入
        if (this.$route && !this.viewDefaultUsage) {
            return false;
        }
        return true;
    }

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    public getDatas(): any[] {
        return [this.context];
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    public getData(): any {
        return this.context;
    }


    /**
     * 视图引擎
     *
     * @private
     * @type {Engine}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    private engine: MobPortalViewEngine = new MobPortalViewEngine();

    /**
     * 引擎初始化
     *
     * @private
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            dashboard: this.$refs.dashboard,
            keyPSDEField: 'crm_lead',
            majorPSDEField: 'name',
            isLoadDefault: true,
        });
    }

    /**
     * Vue声明周期
     *
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof Crm_leadMobMainDashboardViewBase
     */    
    protected afterCreated(){
        const secondtag = this.$util.createUUID();
        this.$store.commit('viewaction/createdView', { viewtag: this.viewtag, secondtag: secondtag });
        this.viewtag = secondtag;
        this.parseViewParam();

    }

    /**
     * 销毁之前
     *
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected beforeDestroy() {
        this.$store.commit('viewaction/removeView', this.viewtag);
    }

    /**
     * Vue声明周期(组件初始化完毕)
     *
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected mounted() {
        this.afterMounted();
    }

    /**
     * 执行mounted后的逻辑
     * 
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected afterMounted(){
        const _this: any = this;
        _this.engineInit();
        if (_this.loadModel && _this.loadModel instanceof Function) {
            _this.loadModel();
        }

    }

    /**
     * 销毁视图回调
     *
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected destroyed(){
        this.afterDestroyed();
    }

    /**
     * 执行destroyed后的逻辑
     * 
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected afterDestroyed(){
        if (this.viewDefaultUsage && Object.keys(localStorage).length > 0) {
            Object.keys(localStorage).forEach((item: string) => {
                if (item.startsWith(this.context.srfsessionid)) {
                    localStorage.removeItem(item);
                }
            });
        }

    }

    /**
     * dashboard 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected dashboard_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('dashboard', 'load', $event);
    }


    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    protected closeView(args: any[]): void {
        if (this.viewDefaultUsage) {
            this.$store.commit("deletePage", this.$route.fullPath);
            this.$router.go(-1);
        } else {
            this.$emit("close", { status: "success", action: "close", data: args instanceof MouseEvent ? null : args });
        }
    }

    /**
     * 刷新数据
     *
     * @readonly
     * @type {(number | null)}
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    get refreshdata(): number | null {
        return this.$store.getters['viewaction/getRefreshData'](this.viewtag);
    }

    /**
     * 监控数据变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @returns
     * @memberof Crm_leadMobMainDashboardViewBase
     */
    @Watch('refreshdata')
    onRefreshData(newVal: any, oldVal: any) {
        if (newVal === null || newVal === undefined) {
            return;
        }
        if (newVal === 0) {
            return;
        }
        const _this: any = this;
        if (_this.onRefreshView && _this.onRefreshView instanceof Function) {
            _this.onRefreshView();
        }
    }


}
</script>

<style lang='less'>
@import './crm-lead-mob-main-dashboard-view.less';
</style>